package com.bckj.fastboot.auth.custom.sms;

import com.bckj.fastboot.auth.base.BaseAuthenticationConverter;
import com.bckj.fastboot.auth.custom.sms.SmsAuthenticationToken;
import com.bckj.fastboot.security.constant.SecurityConstants;
import com.bckj.fastboot.security.util.OAuth2EndpointUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Set;

/**
 * 短信登录转换器
 */
public class SmsAuthenticationConverter
		extends BaseAuthenticationConverter<SmsAuthenticationToken> {

	/**
	 * 是否支持此convert
	 * @param grantType 授权类型
	 */
	@Override
	public boolean support(String grantType) {
		return SecurityConstants.GRANT_TYPE_SMS.equals(grantType);
	}

	@Override
	public SmsAuthenticationToken buildToken(Authentication clientPrincipal, Set<String> requestedScopes,
											 Map<String, Object> additionalParameters) {
		return new SmsAuthenticationToken(new AuthorizationGrantType(SecurityConstants.GRANT_TYPE_SMS),
				clientPrincipal, requestedScopes, additionalParameters);
	}

	/**
	 * 校验扩展参数 密码模式密码必须不为空
	 * @param request 参数列表
	 */
	@Override
	public void checkParams(HttpServletRequest request) {
		MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getParameters(request);
		// PHONE (REQUIRED)
		String phone = parameters.getFirst(SecurityConstants.OAUTH_PARAMETER_NAME_SMS_PHONE);
		if (!StringUtils.hasText(phone) || parameters.get(SecurityConstants.OAUTH_PARAMETER_NAME_SMS_PHONE).size() != 1) {
			OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, "手机号不能为空",
					OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI);
		}
		String code = parameters.getFirst(SecurityConstants.OAUTH_PARAMETER_NAME_SMS_VERIFICATION_CODE);
		if (!StringUtils.hasText(code) || parameters.get(SecurityConstants.OAUTH_PARAMETER_NAME_SMS_VERIFICATION_CODE).size() != 1) {
			OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, "验证码不能为空",
					OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI);
		}
	}

}
